package controller

import (
	"fmt"
	"net/http"
	"news/models"
	"news/utils"

	jwt "github.com/appleboy/gin-jwt/v2"
	"github.com/gin-gonic/gin"
	"golang.org/x/crypto/bcrypt"
)

// CreateUser 创建用户
func CreateUser(c *gin.Context) {
	var user models.User
	c.BindJSON(&user)
	hash, err := bcrypt.GenerateFromPassword([]byte(user.PassWord), bcrypt.MinCost)
	if err != nil {
		fmt.Println(err)
	}
	user.PassWord = string(hash)
	err = models.CreateUser(&user)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"error": err.Error()})
	} else {
		c.JSON(http.StatusOK, utils.ResultBulid(user))
	}
}

// GetAllUser 获取全部用户信息
func GetAllUser(c *gin.Context) {
	claims := jwt.ExtractClaims(c)
	fmt.Println(claims)
	var userList, err = models.GetAllUser()
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"error": err.Error()})
	} else {
		c.JSON(http.StatusOK, utils.ResultBulid(userList))
	}
}

// UpdateAUser 更新一个用户
func UpdateAUser(c *gin.Context) {
	id, ok := c.Params.Get("id")
	if !ok {
		c.JSON(http.StatusOK, gin.H{"error": "无效的id"})
		return
	}
	user, err := models.GetAUser(id)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"error": err.Error()})
		return
	}
	c.BindJSON(&user)
	if err = models.UpdateAUser(user); err != nil {
		c.JSON(http.StatusOK, gin.H{"error": err.Error()})
	} else {
		c.JSON(http.StatusOK, utils.ResultBulid(user))
	}
}

// DeleteAUser 删除一个用户
func DeleteAUser(c *gin.Context) {
	id, ok := c.Params.Get("id")
	if !ok {
		c.JSON(http.StatusOK, gin.H{"error": "无效的id"})
		return
	}
	if err := models.DeleteAUser(id); err != nil {
		c.JSON(http.StatusOK, gin.H{"error": err.Error()})
	} else {
		c.JSON(http.StatusOK, utils.ResultBulid(id+" deleted。"))
	}
}
